package com.cy.pj.sys.controller;

import com.cy.pj.common.vo.JsonResult;
import com.cy.pj.sys.entity.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RequestMapping("/user")
@RestController
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    //查询所有用户信息
    @RequestMapping("/doFindPageObjects")
    public JsonResult doFindPageObjects(
            String username,Integer pageCurrent){
        return new JsonResult(
                sysUserService.findPageObjects(username, pageCurrent));
    }


    @RequestMapping("/doValidById")
    public JsonResult doValidById(Integer id,Integer valid){
        sysUserService.validById(id, valid);
        return new JsonResult("update ok");
    }

    //保存用户信息以及用户角色相关数据
    @RequestMapping("/doSaveObject")
    public JsonResult doSaveObject(SysUser entity,
                                   Integer[] roleIds){
        sysUserService.saveObject(entity, roleIds);
        return new JsonResult("save ok");
    }
    
    //基于用户id查询用户及相关信息
    @RequestMapping("/doFindObjectById")
    public JsonResult doFindObjectById(Integer id){
        Map<String, Object> map = sysUserService.findObjectById(id);
        return new JsonResult(map);
    }

    //基于用户更新数据,更新用户信息
    @RequestMapping("/doUpdateObject")
    public JsonResult doUpdateObject(SysUser entity, Integer[] roleIds){
//        System.out.println(entity.getDeptId());
        sysUserService.updateObject(entity, roleIds);
        return new JsonResult("update ok");
    }

    //基于用户id修改密码
    @RequestMapping("/doUpdatePassword")
    public JsonResult doUpdatePassword(String pwd,
                                       String newPwd,
                                       String cfgPwd){
        sysUserService.updatePassword(pwd, newPwd, cfgPwd);
        return new JsonResult("update password ok");
    }

    //定义用户登录方法
    @RequestMapping("/doLogin")
    public JsonResult doLogin(String username,String password){
        //1.获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //2.通过Subject提交用户信息,交给shiro框架进行认证操作
        //2.1 对用户进行封装
        UsernamePasswordToken token =
                new UsernamePasswordToken(username,password);
        //2.2对用户信息进行身份认证
        subject.login(token); //提交给securityManager
        return new JsonResult("login ok");
    }
}
